package com.tczs.dispatch;

import com.tczs.dispatch.response.MappingResponse;
import com.tczs.dispatch.response.ResponseResult;
import com.tczs.server.action.ServerExecute;
import com.tczs.server.request.ServerRequestModel;
import com.tczs.server.response.Response;
import io.netty.handler.codec.http.FullHttpResponse;
import org.apache.log4j.Logger;

public abstract class AbstractServerExecute implements ServerExecute {
    private static Logger logger = Logger.getLogger(AbstractServerExecute.class);

    public abstract ServerRequestModel beforeExecute(ServerRequestModel serverRequestModel);

    public FullHttpResponse dispatchExecute(ServerRequestModel serverRequestModel,Handler handler) {
        if(serverRequestModel.getUrl().startsWith("/html")){
            return Response.okStaticFileResponse("."+serverRequestModel.getUrl());
        }
        ResponseResult result = DispatchRequest.dispatch(serverRequestModel,handler);
        FullHttpResponse fullHttpResponse = MappingResponse.mappingHttpResponse(result);
        return fullHttpResponse;
    }

    public abstract FullHttpResponse afterExecute(FullHttpResponse fullHttpResponse);


    @Override
    public FullHttpResponse execute(ServerRequestModel serverRequestModel) {
        Handler handler =  CollectAction.handlers.get(serverRequestModel.getUrl());
        if(handler == null){
            logger.error("your url is not found:"+serverRequestModel.getUrl());
            return Response.notFoundResponse();
        }
        Object obj = CollectAction.objects.get(handler.getClazz());
        ServerRequestModel serverRequest= beforeExecute(serverRequestModel);
        FullHttpResponse fullHttpResponse = dispatchExecute(serverRequest,handler);
        FullHttpResponse response = afterExecute(fullHttpResponse);
        return response;
    }

}
